package com.ctg.behavior.calc.impala.transfer.tracks;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtCalcDate;
import com.ctg.behavior.calc.common.CtSQLConsts;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.utils.CtCalcDaysUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.tracks.CtTracksBody;
import com.ctg.behavior.utils.CtDateUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtTracksUnionTransfer implements CtSQLTransfer {

	@Autowired
	private CtTracksTransfer tracksTransfer;

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtTracksBody)) {
			log.warn("calcObject is not CtTracksBody, class={}", calcObject.getClass());
			return "";
		}
		CtTracksBody calcBody = (CtTracksBody) calcObject;
		log.info("CtTracksBody={}", JSON.toJSONString(calcBody));

		// 组装SQL
		StringBuilder impalaSQL = new StringBuilder();

		Date fromDate = CtDateUtils.stringToDate(calcBody.getStartTime());
		if(StringUtils.isEmpty(calcBody.getEndTime())) {
			calcBody.setEndTime(CtDateUtils.dateToString(new Date()));
		}
		Date toDate = CtDateUtils.stringToDate(calcBody.getEndTime());
		CtCalcDate calcDate = new CtCalcDate();
		calcDate.setFromDate(fromDate);
		calcDate.setToDate(toDate);

		if (CtCalcDaysUtils.isOnlyToday(calcDate)) {
			CtSQLParam rtSQLParam = CtSQLParam.createParam();
			rtSQLParam.addParam(CtSQLConsts.KEY_IS_RT_DATA, "TRUE");
			String rtDetailSQL = tracksTransfer.doTransfer(calcObject, rtSQLParam);
			impalaSQL.append(rtDetailSQL);
		} else {
			Boolean isRealTimeData = CtCalcDaysUtils.isContainToday(calcDate);
			if (isRealTimeData) {
				CtSQLParam rtSQLParam = CtSQLParam.createParam();
				rtSQLParam.addParam(CtSQLConsts.KEY_IS_RT_DATA, "TRUE");
				String rtDetailSQL = tracksTransfer.doTransfer(calcObject, rtSQLParam);
				impalaSQL.append(rtDetailSQL).append("  UNION  ");
			}
			String detailSQL = tracksTransfer.doTransfer(calcObject, sqlParam);
			impalaSQL.append(detailSQL);
		}

		return impalaSQL.toString();
	}

}
